package com.wanlian.router.ui.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.widget.Toast;

import com.wanlian.router.R;
import com.wanlian.router.net.internal.DownLoadTask;
import com.wanlian.router.utils.Utils;
import com.wanlian.router.widget.NumberProgressBar;

import java.io.File;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Hyu on 2018/9/18.
 * Email: fvaryu@163.com
 */
public class UpgradeDownDialog extends Dialog {

    private Activity mActivity;
    @BindView(R.id.num_progress)
    NumberProgressBar num_progress;

    public UpgradeDownDialog(Activity activity) {
        super(activity, R.style.UpgradeDialog);
        mActivity = activity;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.dialog_upgrade_down);
        ButterKnife.bind(this);

        setCancelable(false);
        setCanceledOnTouchOutside(false);
    }


    @Override
    protected void onStart() {
        super.onStart();
    }

    public UpgradeDownDialog start(String url) {
        new DownLoadTask(getContext())
                .startDownload(new DownLoadTask.FileInfo(String.format(Locale.getDefault(),"wl_%d.apk",
                        System.currentTimeMillis()), url), new DownLoadTask.DownloadFileTaskFinishListener() {
            @Override
            public void onProgress(int progress) {
                num_progress.setProgress(progress);
            }

            @Override
            public void onDownloadFinished(File file) {

                if (file == null) {
                    Toast.makeText(mActivity, "网络错误,请重试", Toast.LENGTH_SHORT).show();
                    dismiss();
                    return;
                }
                Utils.install(mActivity, file);
            }
        });
        return this;
    }
}
